<?php
namespace tp5_lib\wechat\utility;

use think\facade\Env;
use think\Db;


class WechatOAuth
{
    protected $appid;
    protected $secret;
    protected $key;
    /**
     * @param string $appid AppID
     * @param string $secret AppSecret
     * @param string $key EncodingAESKey
     * @return self
     */
    static public function alloc($appid,$secret,$key="")
    {
        $new=new self;
        $new->appid=$appid;
        $new->secret=$secret;
        $new->key=$key;
        return $new;
    }
    /**
     * 获取扫码登录页面的链接
     * 必须有网站应用的权限
     */
    public function getScanLoginUrl($redirect_uri,$state="")
    {
        $redirect_uri=urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/qrconnect?appid={$this->appid}&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_login&state=$state#wechat_redirect";
    }
    /**
     * 获取网页授权页面的链接
     * 必须有公众号的权限
     */
    public function getWebpageAuthUrl($redirect_uri,$scope="snsapi_userinfo",$state="")
    {
        $redirect_uri=urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=$state#wechat_redirect";
    }
    /** 
     * 获取访问令牌
     * 包含排除重复code的功能
{
    "access_token":"19_FRJtRKJ2q7Q9zdAM0f2LBv9cG4tTK-tK6MErZ4LKWgu1kocf-Vp1TiyBO5u5bOb16GfntH42bws3MCLd4TY_0w",
    "expires_in":7200,
    "refresh_token":"19_lmPkMWIe25uug7WF-HVgzK8JctiJon9sAXnFwJiX0uZYKMFq82q62TY2nocoE1jHoXVZlHt2MTCA3XsrzyP6Yw",
    "openid":"ovnc91I3Ra4JRE8ZsZHj5C2MPx9M",
    "scope":"snsapi_login",
    "unionid":"odNGz0optCK1Y6Nv47lMypQuQUqs"
}
     */
    public function getAccessToken($code)
    {
        // $dir=Env::get("runtime_path")."wechat_code";
        // if(!file_exists($dir)){
        //     mkdir($dir);
        // }
        // $path=$dir."/".$code;
        // if(file_exists($path)){
        //     $file=fopen($path,"r");
        //     flock($file,LOCK_EX);
        //     $response=fread($file,10000);
        //     flock($file,LOCK_UN);
        //     fclose($file);
        // }
        // else{
        //     $file=fopen($path,"w+");
        //     flock($file,LOCK_EX);
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->secret}&code=$code&grant_type=authorization_code";
            $response=$this->post($url,[]);
            // fwrite($file,$response);
            // flock($file,LOCK_UN);
            // fclose($file);
        // }
        return json_decode($response,true);
    }
    /**
{
    "access_token":"19_6T7BQW1wQXLPy9x4LbgcgrYNJULq5hztZV35t6j_tQcw-qjg9ZSIOdgrKsAoimFMSqqTSP5J9QRu4RVB38G_vYggdDJwOnKVWF7frb2mbWie4Fl9QDKEKwurObMs3ZexXJjp_rjXEKWzLlZKIVOeAHAANG", 
    "expires_in": 7199
}
     */
    public function refreshToken($refresh_token)
    {
        $url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token=$refresh_token";
        $response=$this->post($url,[]);
        return json_decode($response,true);
    }
    /**
{
    "errcode"=>0,
    "errmsg"=>"ok"
}
     */
    public function checkAccessToken($openid,$access_token)
    {
        $url="https://api.weixin.qq.com/sns/auth?openid=$openid&access_token=$access_token";
        $response=$this->post($url,[]);
        return json_decode($response,true);
    }
    /**
{
    "openid":"ovnc91I3Ra4JRE8ZsZHj5C2MPx9M",
    "nickname":"阿银",
    "sex":1,
    "language":"zh_CN",
    "city":"",
    "province":"",
    "country":"KY",
    "headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/zZ4fjReKKe6jSTeqgfQuzH3ic4cpNxcapfD9PkEgaLPJlRKIzVDataoQQkSOdLqzqG143UbrmQ50GibLR0ZzOg8w\/132",
    "privilege":[],
    "unionid":"odNGz0optCK1Y6Nv47lMypQuQUqs"
}
     */
    public function getUserInfo($openid,$access_token)
    {
        $url="https://api.weixin.qq.com/sns/userinfo?openid=$openid&access_token=$access_token";
        $response=$this->post($url,[]);
        return json_decode($response,true);
    }
    public function post($url,$data)
    {
        $data=json_encode($data,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);// POST方式发送
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);// post的数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
